package com.partsoft.webs.spring;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.springframework.web.filter.GenericFilterBean;

/**
 * 平台所有的过滤器委派接口(不需要设置一大串的过滤器列表）
 * 
 * @author neeker
 */
@Deprecated
public class DelegatingFilter extends GenericFilterBean {

	private String targetBeanName;

	private Filter delegate;

	private final Object delegateMonitor = new Object();

	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException,
			ServletException {

		Filter delegateToUse = null;
		synchronized (this.delegateMonitor) {
			if (this.delegate == null) {
				WebApplicationContext wac = findWebApplicationContext();
				if (wac == null) {
					throw new IllegalStateException(
							"No WebApplicationContext found: no ContextLoaderListener registered?");
				}
				this.delegate = initDelegate(wac);
			}
			delegateToUse = this.delegate;
		}

		invokeDelegate(delegateToUse, request, response, chain);

	}

	protected WebApplicationContext findWebApplicationContext() {
		return WebApplicationContextUtils.getWebApplicationContext(getServletContext());
	}

	protected Filter initDelegate(WebApplicationContext wac) throws ServletException {
		Filter delegate = (Filter) wac.getBean(getTargetBeanName(), Filter.class);

		delegate.init(getFilterConfig());
		return delegate;
	}

	protected void invokeDelegate(Filter delegate, ServletRequest request, ServletResponse response, FilterChain chain)
			throws ServletException, IOException {

		delegate.doFilter(request, response, chain);
	}

	public String getTargetBeanName() {
		return targetBeanName;
	}

	protected void initFilterBean() throws ServletException {
		if (this.targetBeanName == null) {
			this.targetBeanName = "delegatingFilterProxy";
		}

		synchronized (this.delegateMonitor) {
			WebApplicationContext wac = findWebApplicationContext();
			if (wac != null) {
				this.delegate = initDelegate(wac);
			}
		}

	}

	public void destroy() {
		Filter delegateToUse = null;
		synchronized (this.delegateMonitor) {
			delegateToUse = this.delegate;
		}
		if (delegateToUse != null) {
			delegate.destroy();
		}
	}

}
